package com.funo.logic.controller;

import cn.hutool.json.JSONUtil;
import com.funo.logic.model.LogicConfig;
import com.funo.logic.model.QueryResponse;
import com.funo.logic.response.HandleResult;
import com.funo.logic.service.CompilationInParameterService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 逻辑配置controller
 */
@RestController
@RequestMapping("logicConfig")
public class LogicConfigController extends AbstractController{

    private static final String NODE_NAME = "逻辑判断";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CompilationInParameterService compilationInParameterService;

    /**
     * 保存或者更新逻辑配置
     * @param logicConfig
     * @return HandleResult
     * @since 2024年7月19日16:23:16
     * @author cms
     */
    @PostMapping("saveOrUpdate")
    public HandleResult saveOrUpdate(@RequestBody LogicConfig logicConfig) {
        String belongNodeId = logicConfig.getBelongNodeId();
        String cacheKey = getCacheKey(belongNodeId);

        QueryResponse queryResponse = new QueryResponse();
        queryResponse.setBelongNodeId(logicConfig.getBelongNodeId());
        queryResponse.setNodeName(logicConfig.getBelongNodeId());
        // 后端判断只返回HandleResult的code和message
        queryResponse.setColumnList(Lists.newArrayList("code", "message"));
        compilationInParameterService.addOrUpdateLogicConfigResponse(logicConfig.getArrangeId(), queryResponse);

        stringRedisTemplate.delete(cacheKey);
        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(logicConfig));
        return HandleResult.success();
    }

    /**
     * 根据所属模块id查询
     * @param belongNodeId
     * @return HandleResult
     * @since 2024年7月19日16:28:23
     * @author cms
     */
    @GetMapping("getByBelongNodeId")
    public HandleResult getByBelongNodeId(String belongNodeId) {
        String cacheKey = getCacheKey(belongNodeId);
        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(cacheValue)) {
            return HandleResult.noData();
        }
        return HandleResult.success(JSONUtil.toBean(cacheValue, LogicConfig.class));
    }


    public String getCachePrefix() {
        return "logicConfig:";
    }
}
